function addInputGrid(obj,name,file)
%this function loads an input data file inside DisplayWidget. All
%interesting info is stored in TreeWidget, so the user can change it
%afterwards.
% INPUT DATA:
%   - obj: the object which calls this function.
%   - name: the name given to the grid. Name == grid kind.
%   - file: the file (including path) of the file with the data.

% This file is part of CISNE.
%
%     CISNE is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     any later version.
%
%     CISNE is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with CISNE.  If not, see <http://www.gnu.org/licenses/>.

% Copyright 2011. Jose Maria Garcia-Valdecasas Bernal

%we need to recover handle structure so that we can interact with
%TreeWidget.
handles=guidata(obj.m_Figure);

switch name
    
    case {'BATHYMETRY', 'VEGETATION', 'FRICTION'}

%check file type and how to load the data
fh1=fopen(file);
line=fgetl(fh1);%read first line and close file.
fclose(fh1);
if strcmp(line,'DSAA') %surfer ASCII Grid file
    
    %use function to read surfer grid files.
    [data xmin xmax ymin ymax]=readGrd(file,handles.jProgressBar,...
        handles.jStatusBar);
    
    %store data in TreeWidget using setValue function.
    handles.TreeWidget.setValue('Xmin',xmin,name);
    handles.TreeWidget.setValue('Ymin',ymin,name);
    [m,n]=size(data);
    handles.TreeWidget.setValue('Nx',n,name);
    handles.TreeWidget.setValue('Ny',m,name);
    handles.TreeWidget.setValue('X Step',(xmax-xmin)/(n-1),name);
    handles.TreeWidget.setValue('Y Step',(ymax-ymin)/(m-1),name);
    handles.TreeWidget.setValue('Header',5,name);
    handles.TreeWidget.setValue('filetype',4,name);
    handles.TreeWidget.setValue('File',file,name);
    handles.TreeWidget.setValue('Flip',true,name);
    
    
else %let's suppose that we are handling a delimited matrix
    try 
        data=dlmread(file);
        if (~isempty(data))
            [m,n]=size(data);
            handles.TreeWidget.setValue('Nx',n,name);
            handles.TreeWidget.setValue('Ny',m,name);
            handles.TreeWidget.setValue('filetype',1,name);
            handles.TreeWidget.setValue('Header',0,name);
            handles.TreeWidget.setValue('File',file,name);
            handles.TreeWidget.setValue('Flip',false,name);
            xmin=handles.TreeWidget.getValue('Xmin',name);
            ymin=handles.TreeWidget.getValue('Ymin',name);
            dx=handles.TreeWidget.getValue('X Step',name);
            dy=handles.TreeWidget.getValue('Y Step',name);
            xmax=dx*(n-1)+xmin;
            ymax=dy*(m-1)+ymin;
        end
            
    catch ME
        [data,header,nx,ny]=readCustomFormat(file,handles.jProgressBar,...
        handles.jStatusBar);
        handles.TreeWidget.setValue('Nx',nx,name);
        handles.TreeWidget.setValue('Ny',ny,name);
        handles.TreeWidget.setValue('filetype',2,name);
        handles.TreeWidget.setValue('Header',header,name);
        handles.TreeWidget.setValue('File',file,name);
        handles.TreeWidget.setValue('Flip',false,name);
        xmin=handles.TreeWidget.getValue('Xmin',name);
        ymin=handles.TreeWidget.getValue('Ymin',name);
        dx=handles.TreeWidget.getValue('X Step',name);
        dy=handles.TreeWidget.getValue('Y Step',name);
        xmax=dx*(nx-1)+xmin;
        ymax=dy*(ny-1)+ymin;
        
    end
end

%OK, we have already all the data, let's handle it inside DisplayWidget
obj.m_inputGrids.(name).method='image'; %display method (image, contour...)
obj.m_inputGrids.(name).alpha=1; %opacity percentage (for images).
obj.m_inputGrids.(name).data=data; %grid data, so we can display it.

    otherwise %Current and Wind!! (file contains 2 data matrix) 
        try 
        data=dlmread(file);
        if (~isempty(data))
            [m,n]=size(data);
            data=reshape(data,m/2,n,2);
            handles.TreeWidget.setValue('Nx',n,name);
            handles.TreeWidget.setValue('Ny',m/2,name);
            handles.TreeWidget.setValue('filetype',1,name);
            handles.TreeWidget.setValue('Header',0,name);
            handles.TreeWidget.setValue('File',file,name);
            handles.TreeWidget.setValue('Flip',false,name);
            xmin=handles.TreeWidget.getValue('Xmin',name);
            ymin=handles.TreeWidget.getValue('Ymin',name);
            dx=handles.TreeWidget.getValue('X Step',name);
            dy=handles.TreeWidget.getValue('Y Step',name);
            xmax=dx*(n-1)+xmin;
            ymax=dy*(m-1)+ymin;
        end
            
        catch ME
        [data,header,nx,ny]=readCustomFormat(file,handles.jProgressBar,...
        handles.jStatusBar,2);
        handles.TreeWidget.setValue('Nx',nx,name);
        handles.TreeWidget.setValue('Ny',ny,name);
        handles.TreeWidget.setValue('filetype',2,name);
        handles.TreeWidget.setValue('Header',header,name);
        handles.TreeWidget.setValue('File',file,name);
        handles.TreeWidget.setValue('Flip',false,name);
        xmin=handles.TreeWidget.getValue('Xmin',name);
        ymin=handles.TreeWidget.getValue('Ymin',name);
        dx=handles.TreeWidget.getValue('X Step',name);
        dy=handles.TreeWidget.getValue('Y Step',name);
        xmax=dx*(nx-1)+xmin;
        ymax=dy*(ny-1)+ymin;
        
        end
        obj.m_inputGrids.(name).method='quiver';
        obj.m_inputGrids.(name).data=data;
    
end
%Draw the image :)
obj.drawIGrid(name);

%is this the first image? Did the user config Axes limits?
checkAxLimits(obj,xmin,xmax,ymin,ymax);


%%%%%%%%%%%%%%%%%

function checkAxLimits(obj,xmin,xmax,ymin,ymax)
if xmin~=xmax&&ymin~=ymax
xlim=get(obj.m_inputAx,'XLim');
ylim=get(obj.m_inputAx,'YLim');
if (xmin<xlim(1))||(xmax>xlim(2))||(ymin<ylim(1))||(ymax>ylim(2))

    answer = questdlg('Image limits are outside axes limits. Update to fit image limits?',...
        'AXES LIMITS','yes','no','yes');
    if strcmp(answer,'yes')
        set(obj.m_inputAx,'XLim',[xmin xmax],'YLim',[ymin ymax]);
        set(obj.m_compAx,'XLim',[xmin xmax],'YLim',[ymin ymax]);
        obj.setAxesLimits(xmin,xmax,ymin,ymax);
    end
end
end

function [matrix xmin xmax ymin ymax]=readGrd(namefile,pBar,sBar)

grdfile=fopen(namefile,'r');    % Open file
fgetl(grdfile);            % Reads surfer code 'DSAA'
% Grid dimensions (number of nodes)
aux=str2num(fgetl(grdfile)); nx=aux(1); ny=aux(2); %#ok<ST2NM>
% X limits
aux=str2num(fgetl(grdfile)); xmin=aux(1); xmax=aux(2); %#ok<ST2NM>
% Y limits
aux=str2num(fgetl(grdfile)); ymin=aux(1); ymax=aux(2); %#ok<ST2NM>
% Z limits (ignored as we do not need them)
fgetl(grdfile);

% Add a progress-bar to left side of standard MJStatusBar container
set(pBar,'StringPainted','on','Minimum',0, 'Maximum',ny, 'Value',0);
sBar.setText('Loading data file...');
pBar.setValue(0);
pBar.setVisible(1);
% Read matrix
matrix=zeros(ny,nx);
for jj=1:ny
            
    row=textscan(grdfile,'%f',nx);
    matrix(jj,:)=cell2mat(row);
    %update progress bar to avoid loosing patience
   
    pBar.setValue(jj);
end

pBar.setVisible(0);
sBar.setText('Grid Data succesfully loaded');
fclose(grdfile);


function [matrix,header,nx,ny]=readCustomFormat(file,pBar,sBar,n)
%read grid data from file with custom format. n= number of grids. For
%current and wind n=2.

if nargin==3
    n=1;
end

answer=inputdlg({'Number of header lines:',...
    'Number of elements in X direction',...
    'Number of elements in Y direction'} ,'Custom Input Grid Filetype');
nx=str2double(answer{1});
ny=str2double(answer{2});
header=str2double(answer{3});

grdfile=fopen(file,'r');    % Open file

% Add a progress-bar to left side of standard MJStatusBar container
set(pBar,'StringPainted','on','Minimum',0, 'Maximum',ny*n, 'Value',0);
sBar.setText('Loading data file...');
pBar.setValue(0);
pBar.setVisible(1);
% Read matrix
matrix=zeros(ny,nx,n);
aux=1;
for k=1:n
    for jj=1:ny
        row=textscan(grdfile,'%f',nx);
        matrix(jj,:,n)=cell2mat(row);
        pBar.setValue(aux);
        aux=aux+1;
    end
end
pBar.setVisible(0);
sBar.setText('Bathymetry succesfully loaded');
fclose(grdfile);
        
